package tiandang.core.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.ZonedDateTime;
import java.util.Properties;

@Service
@PropertySource("classpath:/mail.properties")
public class ReportService {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Value("${mail.from}")
  private String from;

  @Value("${mail.passord}")
  private String passord;

  @Value("${mail.to}")
  private String to;

  // http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mail.html
  JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

  /**
   * 发普通邮件
   */
  @Async
  public void sendSimpleMail(String subject, String content) {
    logger.info("************开始发送邮件了*********");
    SimpleMailMessage msg = new SimpleMailMessage();
    // 设置发送邮件服务信息
    javaMailSender.setHost("smtp.163.com");
    javaMailSender.setPort(465);
    javaMailSender.setUsername(from);
    javaMailSender.setPassword(passord);
    javaMailSender.setJavaMailProperties(new Properties() {
      {
        put("mail.transport.protocol", "smtp");
        put("mail.smtp.auth", true);
        put("mail.smtp.starttls.enable", true);
        put("mail.debug", true);
        put("mail.smtp.ssl.enable", true);
      }
    });
    msg.setFrom(from);
    msg.setTo(to.split(";"));
    msg.setSubject(subject);
    msg.setText(content);
    try {
      javaMailSender.send(msg);
      logger.info("************邮件发送成功了*********");
    } catch (Exception x) {
      logger.error("邮件发送失败：", x);
    }
  }

  /**
   * 发异常消息邮件
   */
  @Async
  public void sendExceptionMail(Exception ex, String requestUrl, String formData, String requestHeader) {
    logger.info("************开始发送异常消息邮件了*********");
    SimpleMailMessage msg = new SimpleMailMessage();
    // 设置发送邮件服务信息
    javaMailSender.setHost("smtp.163.com");
    javaMailSender.setPort(465);
    javaMailSender.setUsername(from);
    javaMailSender.setPassword(passord);
    javaMailSender.setJavaMailProperties(new Properties() {
      {
        put("mail.transport.protocol", "smtp");
        put("mail.smtp.auth", true);
        put("mail.smtp.starttls.enable", true);
        put("mail.debug", true);
        put("mail.smtp.ssl.enable", true);
      }
    });
    msg.setFrom(from);
    msg.setTo(to.split(";"));
    msg.setSubject(ZonedDateTime.now().toString() + " " + ex.getClass().getName());
    msg.setText("requestHeader:\t" + requestHeader + "\nrequestUrl:\t" + requestUrl + "\nformData:\t" + formData
      + "\n" + ex.getMessage() + " " + getStackTrace(ex));
    try {
      javaMailSender.send(msg);
      logger.info("************邮件发送成功了*********");
    } catch (Exception x) {
      logger.error("邮件发送失败：", x);
    }
  }

  public static String getStackTrace(final Throwable throwable) {
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw, true);
    throwable.printStackTrace(pw);
    return sw.getBuffer().toString();
  }


}
